<template>
  <list-group datePicker="show"
              :dateModel="dateMonth"
              :dataList.sync="tableData"
              :loading="loading"
              listHeight="calc( 100% - 48px )"
              prop="name"
              :defaultSize="defaultListSize"
              @saveHandler="saveHandler"
              @delHandler="delHandler"
              @addHandler="addHandler"
              @page-handler="getTableData"
              @change="getTableData()"
              @update:dateModel="dateMonth = $event">
    <template v-slot:left="{ item, index }">
      <el-form
        :model="item"
        class="l-h-1-6em"
        label-width="60px"
        :rules="rules"
        :ref="'form1' + index"
      >
        <span v-show="!item.inEdit">
          <div
            :title="item.name"
            class="text-overflow"
          >
            {{ item.name }}
          </div>
        </span>
        <el-form-item
          prop="name"
          v-show="item.inEdit === true"
          :rules="rules.name"
          class="margin-left-xs-60px"
        >
          <el-autocomplete
            class="w-130px"
            ref="autocomplete"
            v-model="item.name"
            :fetch-suggestions="getNameTextList"
            :placeholder="$t('common.pleaseInput')"
            :trigger-on-focus="true"
            :clearable="true"
            @input="validateProp('name', index)"
          >
          <template slot-scope="{ item }">
            <div class="autocompelete-item-container">
              <div class="autocompelete-label" :title="item.value">{{item.value}}</div>
              <i class="iconfont icon-close autocompelete-close" @click.stop="deleteNameTextHandler(item.id)"/>
            </div>
          </template>
          </el-autocomplete>
        </el-form-item>
      </el-form>
    </template>
    <template v-slot:middle="{item,index}">
      <el-form :model="item"
               class="l-h-1-6em"
               label-width="60px"
               :rules="rules"
               :ref="'form2'+index">
        <span class="text-info"
              v-show="item.inEdit!==true">{{$t('common.amount')}}</span>
        <span v-show="item.inEdit!==true">{{parseFloat(item.amount).toFixed(2)}}</span>
        <el-form-item prop="amount"
                      :rules="rules.amount"
                      :label="$t('common.amount')"
                      v-show="item.inEdit===true">
          <el-input v-model="item.amount"
                    class="w-130px"
                    :precision="2"
                    :step="0.1"></el-input>
        </el-form-item>
        <el-form-item prop="date"
                      :rules="rules.date"
                      :label="$t('income.month')"
                      v-show="item.inEdit===true">
          <el-date-picker v-model="item.date"
                          class="w-130px"
                          :picker-options="pickerOptions"
                          v-show="item.inEdit"
                          type="month"></el-date-picker>
        </el-form-item>
      </el-form>
    </template>
  </list-group>
</template>
<script>
import { queryIncomeList, upsertIncome, deleteIncome, queryNameTextList, upsertNameText, deleteNameText } from '@/assets/api'
import { getDateMonth, greaterThanEqualsAfter30Days } from '@/assets/utils/commonUtil'
import ListGroup from '@/components/common/listGroup/Index.vue'
import validationUtil from '@/assets/utils/validationUtil'
const BLUR = 'blur'
export default {
  data () {
    return {
      tableData: {},
      loading: false,
      dateMonth: new Date(),
      defaultListSize: 10,
      autoCompeleteQueryStr: '',
      autoCompeleteCB: {},
      rules: {
        name: [
          { required: true, message: this.$t('validationMessage.inputRequired'), trigger: BLUR }
        ],
        amount: [
          { required: true, message: this.$t('validationMessage.inputRequired'), trigger: BLUR },
          {
            validator: validationUtil.isFloat,
            trigger: BLUR
          }
        ],
        date: [{ required: true, message: this.$t('validationMessage.inputRequired'), trigger: BLUR }]
      },
      pickerOptions: { disabledDate: greaterThanEqualsAfter30Days }
    }
  },
  mounted () {
    this.getTableData()
  },
  components: { ListGroup },
  methods: {
    getTableData (limit = this.defaultListSize, offset = 0) {
      if (limit !== this.defaultListSize) { this.defaultListSize = limit }
      this.loading = true
      if (this.tableData.list) { this.tableData.list.splice(0, this.tableData.list.length) }
      queryIncomeList({ date: getDateMonth(this.dateMonth), limit: limit, offset: offset }).then(res => {
        this.tableData = res.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    delHandler (index) {
      this.loading = true
      deleteIncome({ id: this.tableData.list[index].id }).then(res => {
        this.$message({ type: 'success', message: this.$t('common.deleted') })
        this.getTableData()
        this.$emit('updated')
      })
    },
    saveHandler (index) {
      this.$refs['form1' + index].validate((valid1) => {
        this.$refs['form2' + index].validate((valid) => {
          if (valid1 && valid) {
            this.loading = true
            this.tableData.list[index].date = getDateMonth(this.tableData.list[index].date)
            upsertIncome(this.tableData.list[index]).then(
              res => {
                this.getTableData()
                this.$emit('updated')
              }, () => {
                this.getTableData()
              }
            )
            upsertNameText({ text: this.tableData.list[index].name, type: 'income' })
          }
        })
      })
    },
    addHandler () {
      this.$set(this.tableData.list[0], 'date', this.dateMonth)
    },
    getNameTextList (queryStr, cb) {
      if (queryStr !== null) {
        this.autoCompeleteQueryStr = queryStr
      }
      if (cb) {
        this.autoCompeleteCB = cb
      }
      this.autoCompeleteQueryStr = this.autoCompeleteQueryStr || ''
      queryNameTextList({ type: 'income', searchText: this.autoCompeleteQueryStr }).then(res => {
        const result = res.data.map(item => { item.value = item.text; return item })
        this.autoCompeleteCB(result)
      })
    },
    deleteNameTextHandler (id) {
      deleteNameText({ id: id }).then(res => {
        this.getNameTextList(null, null)
        this.$message({
          type: 'success',
          message: this.$t('common.deleted')
        })
      })
    },
    validateProp (prop, index) {
      this.$refs['form1' + index].validateField(prop)
    }
  }
}
</script>
